package cn.senjoeson.healthsport.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.senjoeson.healthsport.R;
import cn.senjoeson.healthsport.UpdateUiCallBack;
import cn.senjoeson.healthsport.activity.HistoryActivity;
import cn.senjoeson.healthsport.activity.SetPlanActivity;
import cn.senjoeson.healthsport.service.StepService;
import cn.senjoeson.healthsport.utils.SPUtils;
import cn.senjoeson.healthsport.view.StepArcView;

/**
 * Created by senjoeson on 2018/5/26.
 */

public class SportDataFragment extends Fragment implements View.OnClickListener {


    @BindView(R.id.tv_data)
    TextView mTvData;
    @BindView(R.id.cc)
    StepArcView mCc;
    @BindView(R.id.tv_set)
    TextView mTvSet;
    @BindView(R.id.tv_isSupport)
    TextView mTvIsSupport;
    Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_sport, container, false);

        unbinder = ButterKnife.bind(this, view);
        initData();
        addListener();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (isBind) {
            getActivity().unbindService(conn);
        }
    }


    private void addListener() {
        mTvSet.setOnClickListener(this);
        mTvData.setOnClickListener(this);
    }

    private void initData() {
        //设置当前步数为0
        String planWalk_QTY = SPUtils.getString("planWalk_QTY", "10000");
        mCc.setCurrentCount(Integer.parseInt(planWalk_QTY), 0);
        mTvIsSupport.setText("计步中...");
        setupService();
    }


    private boolean isBind = false;

    /**
     * 开启计步服务
     */
    private void setupService() {
        Intent intent = new Intent(getActivity(), StepService.class);
        isBind = getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        getActivity().startService(intent);

    }

    /**
     * 用于查询应用服务（application Service）的状态的一种interface，
     * 更详细的信息可以参考Service 和 context.bindService()中的描述，
     * 和许多来自系统的回调方式一样，ServiceConnection的方法都是进程的主线程中调用的。
     */
    ServiceConnection conn = new ServiceConnection() {
        /**
         * 在建立起于Service的连接时会调用该方法，目前Android是通过IBind机制实现与服务的连接。
         *
         * @param name 实际所连接到的Service组件名称
         * @param service 服务的通信信道的IBind，可以通过Service访问对应服务
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            StepService stepService = ((StepService.StepBinder) service).getService();
            //设置初始化数据
            final String planWalk_QTY = SPUtils.getString("planWalk_QTY", "10000");
            mCc.setCurrentCount(Integer.parseInt(planWalk_QTY), stepService.getStepCount());

            //设置步数监听回调
            stepService.registerCallback(new UpdateUiCallBack() {
                @Override
                public void updateUi(int stepCount) {
                    String planWalk_QTY = SPUtils.getString("planWalk_QTY", "10000");
                    mCc.setCurrentCount(Integer.parseInt(planWalk_QTY), stepCount);
                   // mTvSet.setText(stepCount + "");
                }
            });
        }

        /**
         * 当与Service之间的连接丢失的时候会调用该方法，
         * 这种情况经常发生在Service所在的进程崩溃或者被Kill的时候调用，
         * 此方法不会移除与Service的连接，当服务重新启动的时候仍然会调用 onServiceConnected()。
         * @param name 丢失连接的组件名称
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_set:
                 startActivity(new Intent(getActivity(), SetPlanActivity.class));
                // startActivity(new Intent(getActivity(), RegisterActivity.class));
                break;
            case R.id.tv_data:
                startActivity(new Intent(getActivity(), HistoryActivity.class));
                break;
        }
    }


}
